package com.imooc.coupon.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义异步任务线程池
 *
 * @Author Administrator
 * @Date 2021/10/18 22:08
 * @Version 1.0
 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor exetutor = new ThreadPoolTaskExecutor();
        exetutor.setCorePoolSize(10);
        exetutor.setMaxPoolSize(20);
        exetutor.setKeepAliveSeconds(60);
        exetutor.setQueueCapacity(20);
        exetutor.setThreadNamePrefix("ImoocAsync_");
        exetutor.setWaitForTasksToCompleteOnShutdown(true);
        exetutor.setAwaitTerminationSeconds(60);
        exetutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        exetutor.initialize();

        return exetutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }

    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            throwable.printStackTrace();
            log.error("AsyncError :{},Method :{} ,Parm:{}",
                    throwable.getMessage(), method.getName(), JSON.toJSONString(objects));
            //todo 发送短信，或者做进一步的处理


        }
    }
}
